<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div class="box">
        <!-- 基础理解版 -->
        <div class="demo1">
            <textarea id="text" cols="30" rows="10" placeholder="1、输入文字；2、点击创建文本；3、下载文本"></textarea>
            <input id="btn" type="button" value="创建链接">
            <div id="container"></div>
        </div>
        <!-- 升级：简化操作版 -->
        <div class="demo2">
            <textarea id="demo2Text" cols="30" rows="10" placeholder="输入文字；点击下载文本"></textarea>
            <input id="demo2Btn" type="button" value="下载文件">
        </div>
    </div>
    <script>
        // 基础理解版
        window.onload = function () {
            var textDom = document.getElementById('text')
            var btnDom = document.getElementById('btn')
            var containerDom = document.getElementById('container')

            btnDom.onclick = function () {
                var content = textDom.value
                console.log(content, "content");
                var blob = new Blob([content], { type: "text/plain" })

                containerDom.innerHTML =
                    '<a download="文本" href="' + window.URL.createObjectURL(blob) + '" target="_blank">下载</a>'

            }
        }

        // 升级：简化操作版
        // window.onload = function () {
        var demo2TextDom = document.getElementById('demo2Text')
        var demo2BtnDom = document.getElementById('demo2Btn')

        demo2BtnDom.onclick = function () {
            const content = demo2TextDom.value
            var blob = new Blob([content], { type: 'text/plain' })
            const url = window.URL.createObjectURL(blob)
            var a = document.createElement('a')
            a.download = "download"
            a.href = url

            // 添加元素
            document.body.appendChild(a)

            // 点击a标签
            a.click()

            // 删除a标签
            document.body.removeChild(a)
        }
        // }
    </script>
</body>

<style>
    .box {
        width: 100%;
        display: flex;
        justify-content: space-between;
    }

    .box>div {
        width: 50%;
    }

    #container {
        width: 100px;
        height: 100px;
        border: 2px solid #333;
    }
</style>

</html>